/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package sys.screen;

import java.io.IOException;
import java.sql.SQLException;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.CategoryItemRenderer;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
import sys.bean.PedidoBean;
import sys.dao.PedidoDao;
import sys.utils.Mensagens;
import sys.utils.Utils;
import static sys.utils.Utils.escClose;

/**
 *
 * @author Administrador
 */
public class UITopClientes extends javax.swing.JDialog {

    SimpleDateFormat formDataSpac = new SimpleDateFormat("yyyyMMdd");
    NumberFormat formatoMoeda = NumberFormat.getCurrencyInstance();
    SimpleDateFormat formDataBr = new SimpleDateFormat("dd/MM/yyyy");

    /*    
     *
     * Creates new form UITopClientes
     */
    public UITopClientes(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        setLocationRelativeTo(null);
        dataInicial.setDate(new Date());
        dataFinal.setDate(new Date());
        UIManager.put("Table.alternateRowColor", new java.awt.Color(230, 255, 255));
        escClose(this);
        Utils.maximizarDialog(this);
    }

    private String pNomeCliente(String tx) {
        String[] pNome = tx.split(" ");
        return pNome[0];
    }

    private CategoryDataset cdtTopClientes() {

        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        try {
            List<PedidoBean> listaTopClientes = PedidoDao.topClientesPeriodo(formDataSpac.format(dataInicial.getDate()), formDataSpac.format(dataFinal.getDate()), 50);

            int sizeLista = listaTopClientes.size();
            if (sizeLista > 9) {
                for (int i = 0; i < 10; i++) {
                    dataset.addValue(listaTopClientes.get(i).getvFinal(), pNomeCliente(listaTopClientes.get(i).getCliente().getNome()), "");
                }
            } else {
                for (int i = 0; i < sizeLista; i++) {
                    dataset.addValue(listaTopClientes.get(i).getvFinal(), pNomeCliente(listaTopClientes.get(i).getCliente().getNome()), "");
                }
            }
        } catch (IOException | SQLException ex) {
            Mensagens.msgErro("Erro\n" + ex.getMessage());
        }
        return dataset;
    }

    /*
     * Gerando o grafico de TopClientes (barra)
     *
     */
    private void aGrafTopClientes() {

        CategoryDataset cds = cdtTopClientes();
        //String titulo = "TOP CLIENTES - " + formDataBr.format(dataInicial.getDate()) + " A " + formDataBr.format(dataFinal.getDate());
        String titulo = "";
        String eixoY = "";
        String txLegenda = "";
        boolean legenda = true;
        boolean tooltips = true;
        boolean urls = true;

        JFreeChart graf = ChartFactory.createBarChart(titulo, txLegenda, eixoY, cds, PlotOrientation.VERTICAL, legenda, tooltips, urls);
        CategoryPlot plot = (CategoryPlot) graf.getCategoryPlot();

        CategoryItemRenderer itemRerender = plot.getRenderer();

        itemRerender.setItemLabelGenerator(new StandardCategoryItemLabelGenerator("{2}", NumberFormat.getCurrencyInstance()));
        itemRerender.setItemLabelsVisible(true);

        ChartPanel myChartpanel = new ChartPanel(graf, true);
        myChartpanel.setSize(jpTopClientes.getWidth(), jpTopClientes.getHeight());
        myChartpanel.setVisible(true);
        jpTopClientes.removeAll();
        jpTopClientes.add(myChartpanel);
        jpTopClientes.revalidate();
        jpTopClientes.repaint();
    }

    private void aTabelaTopClientes() {
        DefaultTableModel modelo = (DefaultTableModel) tabela.getModel();

        modelo.setNumRows(0);

        try {
            int cont = 0;
            List<PedidoBean> listaTopClientes = PedidoDao.topClientesPeriodo(formDataSpac.format(dataInicial.getDate()), formDataSpac.format(dataFinal.getDate()), 50);
            for (PedidoBean pedido : listaTopClientes) {
                cont++;
                modelo.addRow(new Object[]{
                    cont, pedido.getCliente().getNome(), formatoMoeda.format(pedido.getvFinal()), pedido.getQtdPedidos()
                });
            }

            DefaultTableCellRenderer esquerda = new DefaultTableCellRenderer();
            DefaultTableCellRenderer centralizado = new DefaultTableCellRenderer();

            esquerda.setHorizontalAlignment(SwingConstants.LEFT);
            centralizado.setHorizontalAlignment(SwingConstants.CENTER);

            tabela.getColumnModel().getColumn(0).setCellRenderer(centralizado);
            tabela.getColumnModel().getColumn(1).setCellRenderer(esquerda);
            tabela.getColumnModel().getColumn(2).setCellRenderer(centralizado);
            tabela.getColumnModel().getColumn(3).setCellRenderer(centralizado);

        } catch (IOException | SQLException ex) {
            Mensagens.msgErro("erro ao autalizar tabela\n" + ex.getMessage());
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jpDados = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        dataInicial = new com.toedter.calendar.JDateChooser("dd/MM/yyyy", "##/##/#####", '_');
        dataFinal = new com.toedter.calendar.JDateChooser("dd/MM/yyyy", "##/##/#####", '_');
        jPanel4 = new javax.swing.JPanel();
        btnBuscar = new javax.swing.JButton();
        btnSair = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        tabela = new javax.swing.JTable();
        jpTopClientes = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("TOP CLIENTES");

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));

        jpDados.setBackground(new java.awt.Color(255, 255, 255));
        jpDados.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "PERÍODO:", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Calibri", 0, 10))); // NOI18N

        jLabel2.setFont(new java.awt.Font("Calibri", 0, 11)); // NOI18N
        jLabel2.setText("DATA INICIAL:");

        jLabel3.setFont(new java.awt.Font("Calibri", 0, 11)); // NOI18N
        jLabel3.setText("DATA FINAL:");

        dataInicial.setFont(new java.awt.Font("Calibri", 0, 12)); // NOI18N

        dataFinal.setFont(new java.awt.Font("Calibri", 0, 12)); // NOI18N

        javax.swing.GroupLayout jpDadosLayout = new javax.swing.GroupLayout(jpDados);
        jpDados.setLayout(jpDadosLayout);
        jpDadosLayout.setHorizontalGroup(
            jpDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpDadosLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(dataInicial, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jpDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jpDadosLayout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(dataFinal, javax.swing.GroupLayout.DEFAULT_SIZE, 130, Short.MAX_VALUE))
                .addGap(12, 12, 12))
        );
        jpDadosLayout.setVerticalGroup(
            jpDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpDadosLayout.createSequentialGroup()
                .addGroup(jpDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(1, 1, 1)
                .addGroup(jpDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(dataInicial, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(dataFinal, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(13, Short.MAX_VALUE))
        );

        jPanel4.setBackground(new java.awt.Color(255, 255, 255));
        jPanel4.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 204, 204)));

        btnBuscar.setFont(new java.awt.Font("Calibri", 0, 13)); // NOI18N
        btnBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sys/picture/find-2.png"))); // NOI18N
        btnBuscar.setText("BUSCAR");
        btnBuscar.setPreferredSize(new java.awt.Dimension(120, 30));
        btnBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBuscarActionPerformed(evt);
            }
        });
        jPanel4.add(btnBuscar);

        btnSair.setFont(new java.awt.Font("Calibri", 0, 13)); // NOI18N
        btnSair.setIcon(new javax.swing.ImageIcon(getClass().getResource("/sys/picture/sair.png"))); // NOI18N
        btnSair.setText("SAIR");
        btnSair.setPreferredSize(new java.awt.Dimension(120, 30));
        btnSair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSairActionPerformed(evt);
            }
        });
        jPanel4.add(btnSair);

        tabela.setAutoCreateRowSorter(true);
        tabela.setFont(new java.awt.Font("Calibri", 0, 12)); // NOI18N
        tabela.setForeground(new java.awt.Color(51, 51, 255));
        tabela.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "POSICAO", "CLIENTE", "TOTAL", "QTD. PEDIDOS"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.Object.class, java.lang.String.class, java.lang.Integer.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tabela.setGridColor(new java.awt.Color(204, 204, 204));
        jScrollPane2.setViewportView(tabela);
        if (tabela.getColumnModel().getColumnCount() > 0) {
            tabela.getColumnModel().getColumn(1).setPreferredWidth(270);
        }

        jpTopClientes.setBackground(new java.awt.Color(255, 255, 255));

        javax.swing.GroupLayout jpTopClientesLayout = new javax.swing.GroupLayout(jpTopClientes);
        jpTopClientes.setLayout(jpTopClientesLayout);
        jpTopClientesLayout.setHorizontalGroup(
            jpTopClientesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 553, Short.MAX_VALUE)
        );
        jpTopClientesLayout.setVerticalGroup(
            jpTopClientesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel4, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jpDados, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 546, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jpTopClientes, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jpDados, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jpTopClientes, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 439, Short.MAX_VALUE))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(1, 1, 1))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuscarActionPerformed
        aTabelaTopClientes();
        aGrafTopClientes();
    }//GEN-LAST:event_btnBuscarActionPerformed

    private void btnSairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSairActionPerformed
        this.dispose();
    }//GEN-LAST:event_btnSairActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnBuscar;
    private javax.swing.JButton btnSair;
    private com.toedter.calendar.JDateChooser dataFinal;
    private com.toedter.calendar.JDateChooser dataInicial;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JPanel jpDados;
    private javax.swing.JPanel jpTopClientes;
    private javax.swing.JTable tabela;
    // End of variables declaration//GEN-END:variables
}
